package utils

import (
	"fmt"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

type MyCustomClaims struct {
	UserId   int    `json:"user_id`
	UserName string `json:"user_name"`
	jwt.RegisteredClaims
}

func CreateJWT(userId int, username string) (string, error) {
	// 创建Claims
	claims := MyCustomClaims{
		userId,
		username,
		jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)), // 过期时间
			IssuedAt:  jwt.NewNumericDate(time.Now()),                     // 签发时间
			NotBefore: jwt.NewNumericDate(time.Now()),                     // 生效时间
			Issuer:    "jediborn",                                         // 签发者
			Subject:   "user-auth",                                        // 主题
			ID:        "unique-id",                                        // Token
		},
	}

	//创建token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	//签名Token(使用密钥)
	secretKey := []byte("admin_server_key")
	signedToken, err := token.SignedString(secretKey)
	if err != nil {
		return "", err
	}
	return signedToken, nil
}

func ParseToken(tokenStr string) (*MyCustomClaims, error) {
	//解析token
	token, err := jwt.ParseWithClaims(tokenStr, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected method: %s", token.Header["alg"])
		}
		return []byte("admin_server_key"), nil
	})
	claims, ok := token.Claims.(*MyCustomClaims)
	if !ok && token.Valid {
		return nil, fmt.Errorf("invalid token claims")
	}
	if err != nil {
		return nil, err
	}
	return claims, nil
}
